package com.yt.app.api.action;

import com.yt.app.api.util.CookieUtils;
import com.yt.app.api.vo.LoginUserVo;
import com.yt.app.core.interfaces.CacheService;
import com.yt.app.core.model.Cache;
import com.yt.app.core.utils.TokenUtil;
import com.yt.core.MsgBean;
import com.yt.util.DateUtils;
import com.yt.util.MD5Util;
import com.yt.util.RandomUtil;
import com.yt.util.SmsUtil;
import com.yt.website.api.interfaces.UserInfoService;
import com.yt.website.api.model.UserInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Api(tags = "01.注册登陆")
@RequestMapping("/user")
//NTpiY2FmMzE5ZTg0ZGQ1NWQxZTQ1ZTJlN2M3MDk1YTIzMQ
public class RegisterAndLoginController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private CacheService cacheService;

    private static String VERIFY_CODE = "VERIFY_CODE";
    private static String SMS_CODE = "SMS_CODE";
    private static String SMS_COUNT = "SMS_COUNT_";
    private static int SMS_LIMIT_PER_DAY = 10;

    @ApiOperation(value="删除用户账号", notes = "仅限测试环境和指定手机号",  httpMethod = "POST")
    @RequestMapping("/deleteMobile")
    public @ResponseBody
    Object deleteMobile(HttpServletRequest request,
                        @ApiParam("手机号") @RequestParam(value = "mobile", required = true, defaultValue = "13521033045") String mobile
                        ) {
        MsgBean msgBean = new MsgBean();
        if(mobile.equals("13521033045") || mobile.equals("15711168890") || mobile.equals("15810099706") || mobile.equals("18610178193")) {
            UserInfo userInfo = userInfoService.getByMobile(mobile);
            if(userInfo != null){
                userInfoService.remove(userInfo.getId());
                cacheService.delCache(SMS_COUNT + mobile);
            }
        }

        return msgBean.returnMsg();
    }

    @ApiOperation(value="获取终端唯一编码", notes = "暂时不用",  httpMethod = "GET")
    @RequestMapping("/getIdentity")
    public @ResponseBody
    Object getIdentity(HttpServletRequest request) {
        MsgBean msgBean = new MsgBean();
        msgBean.put("deviceId", MD5Util.MD5(String.valueOf(System.currentTimeMillis() + RandomUtil.getRandom(10))));
        return msgBean.returnMsg();
    }

    @ApiOperation(value="发送手机验证码", httpMethod = "POST")
    @RequestMapping("/sendSmsCode")
    public @ResponseBody
    Object sendSmsCode(
            @ApiParam("手机号") @RequestParam(value = "mobile", required = true, defaultValue = "0") String mobile,
            //@ApiParam("终端唯一编码，暂时不用") @RequestParam(value = "deviceId", required = true, defaultValue = "0") String deviceId,
            //@ApiParam("验证码") @RequestParam(value = "code", required = true, defaultValue = "0") String code,
            HttpServletRequest request
    ) {
        MsgBean msgBean = new MsgBean();
        /*
        if(!ImageCodeController.checkCode(deviceId, code, cacheService)){

            ImageCodeController.remove(deviceId, code, cacheService);
            return msgBean.failure("验证码错误！").returnMsg();
        }
        //验证成功，删除验证码
        ImageCodeController.remove(deviceId, code, cacheService);
        */
        //验证手机号是否已经存在
        if(!userInfoService.checkMobile(mobile)){
            return msgBean.failure("手机号已存在").returnMsg();
        }


        long lastSentTime = 0l;
        Cache cache = cacheService.getCache(SMS_CODE + "_" +mobile+ "_TIME");
        if (cache != null) {
            lastSentTime = Long.parseLong(cache.getValue());
        }

        long currTime = System.currentTimeMillis() / 1000;
        if (currTime >= lastSentTime + 60) {
            long random = RandomUtil.getRandom(6);
            Cache smsCount = cacheService.getCache(SMS_COUNT + mobile);
            if(smsCount != null){
                Long todayStart = DateUtils.getTodaysFirstSecond(System.currentTimeMillis()/1000);
                Long todayEnd = todayStart + 86400;
                if(smsCount.getExpire() > todayStart && smsCount.getExpire() < todayEnd){
                    int currValue = Integer.parseInt(smsCount.getValue());
                    if(currValue >= SMS_LIMIT_PER_DAY){
                        return msgBean.failure("当日可发送短信条数已用尽，请稍后再试或联系管理员。").returnMsg();
                    }else{
                        cacheService.putCache(SMS_COUNT + mobile, String.valueOf(currValue + 1), System.currentTimeMillis()/1000);
                    }
                }
            }else{
                cacheService.putCache(SMS_COUNT + mobile, String.valueOf(1), System.currentTimeMillis()/1000);
            }

            cacheService.putCache(SMS_CODE + "_" + mobile, String.valueOf(random), System.currentTimeMillis()/1000 + 5 * 60);
            cacheService.putCache(SMS_CODE + "_" + mobile + "_TIME", String.valueOf(currTime), System.currentTimeMillis()/1000 + 5 * 60);
            System.out.println(mobile + "的验证码是：" + random);
            String sms = "感谢您注册怡天网会员，您的验证码是" + random + "，如非本人操作请忽略。";
            boolean result = SmsUtil.send(sms, mobile);
            if(!result){
                return msgBean.failure("验证码发送失败， 请重试！").returnMsg();
            }
        } else {
            return msgBean.failure("60秒内只能发送一次手机验证码，请稍等!").returnMsg();
        }

        return msgBean.returnMsg();
    }


    @ApiOperation(value="注册", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200,message = "用户登陆信息", response = LoginUserVo.class)})
    @RequestMapping("/register")
    public @ResponseBody
    Object register(
            @ApiParam("手机号") @RequestParam(value = "mobile", required = false, defaultValue = "0") String mobile,
            @ApiParam("密码") @RequestParam(value = "password", required = false, defaultValue = "0") String password,
            @ApiParam("用户类型") @RequestParam(value = "userType", required = false, defaultValue = "0") Short userType,
            @ApiParam("验证码") @RequestParam(value = "smsCode", required = false, defaultValue = "0") String smsCode,
            HttpServletRequest request
    ) {
        MsgBean msgBean = new MsgBean();
        Cache cache = cacheService.getCache(SMS_CODE + "_" + mobile);
        boolean codeErr = false;
        if(cache != null){
            if(cache.getValue().equals(smsCode)){
                //验证手机号是否已经存在
                if(!userInfoService.checkMobile(mobile)){
                    return msgBean.failure("手机号已存在").returnMsg();
                }
                UserInfo userInfo = new UserInfo();
                userInfo.setMobile(mobile);
                userInfo.setPassword(MD5Util.MD5(password));
                userInfo.setUserType(userType);

                UserInfo newUser = userInfoService.register(userInfo);
                if(newUser == null){
                    return msgBean.failure("注册失败，请重试！").returnMsg();
                }
                newUser.setNick("爱卿-" + newUser.getId());
                userInfoService.update(newUser);

                msgBean.put("data", makeLoginUserVo(newUser));

                cacheService.remove(cache.getId());
            }else{
                codeErr =  true;
            }
        }else{
            codeErr = true;
        }

        if(codeErr){
            return msgBean.failure("验证码错误！").returnMsg();
        }

        return msgBean.returnMsg();
    }

    @ApiOperation(value="登陆", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200,message = "用户登陆信息", response = LoginUserVo.class)})
    @RequestMapping("/login")
    public @ResponseBody
    Object login(
            @ApiParam("手机号") @RequestParam(value = "mobile", required = false, defaultValue = "0") String mobile,
            @ApiParam("密码") @RequestParam(value = "password", required = false, defaultValue = "0") String password,
            //@ApiParam("终端唯一编码") @RequestParam(value = "deviceId", required = true, defaultValue = "0") String deviceId,
            //@ApiParam("验证码") @RequestParam(value = "code", required = false, defaultValue = "0") String code,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        MsgBean msgBean = new MsgBean();
        /*if(!ImageCodeController.checkCode(deviceId, code, cacheService)){
            ImageCodeController.remove(deviceId, code, cacheService);
            return msgBean.failure("验证码错误！").returnMsg();
        }*/
        UserInfo userInfo = userInfoService.getByMobile(mobile);
        if(userInfo == null){
            return msgBean.failure("登陆失败，手机号不存在!").returnMsg();
        }
        if(!userInfo.getPassword().equals(MD5Util.MD5(password))){
            return msgBean.failure("登陆失败，密码错误!").returnMsg();
        }
        LoginUserVo vo = makeLoginUserVo(userInfo);
        response.addCookie(CookieUtils.createCookie("x-access-token", vo.getToken()));

        msgBean.put("data", vo);

        return msgBean.returnMsg();
    }

    private LoginUserVo makeLoginUserVo(UserInfo userInfo){
        LoginUserVo vo = new LoginUserVo();
        vo.setUid(userInfo.getId());
        vo.setNick(userInfo.getNick());
        vo.setMobile(userInfo.getMobile());
        vo.setIdentify(userInfo.getIdentify());
        vo.setSex(userInfo.getSex());
        vo.setUserIcon(userInfo.getUserIcon());
        vo.setUserType(userInfo.getUserType());
        vo.setToken(TokenUtil.makeToken(userInfo.getId(), userInfo.getPassword(), userInfo.getUserType()));
        vo.setExpire(System.currentTimeMillis()/1000 + Integer.MAX_VALUE);
        return vo;
    }
}
